/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License Version
 *  3 as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
 *  USA.
 */

#include "servertask.h"
#include "scriptenvironment.h"
#include "optrzone.h"

O_Z;

#define optra() OZ

ServerTask::ServerTask(int socketDescriptor, QObject *parent) :
        Task("Optra Tcp Client: " + QString(socketDescriptor) , parent), socketDescriptor(socketDescriptor), client(0)
{
}


void ServerTask::result(const QString& res)
{
    if (client && client->isWritable()){
        optra()->debug(QString("Write result:%1").arg(res));
        client->write(res.toUtf8());
    }
}

void ServerTask::setup()
{
    client = new QTcpSocket(this);
    client->setSocketDescriptor(socketDescriptor);
    qDebug() << "Client connected:" << client->peerAddress().toString();
    optra()->info(QString("Client connected:%1").arg(client->peerAddress().toString()));
    connect(client, SIGNAL(readyRead()), this, SLOT(readyCommand())/*, Qt::DirectConnection*/);
    connect(client, SIGNAL(disconnected()), this, SLOT(disconnected()));

    environment = new ScriptEnvironment(ScriptEnvironment::full, this);
    connect(environment, SIGNAL(output(QString)), this, SLOT(result(QString)));
}

void ServerTask::cleanup()
{
    client->deleteLater();
    environment->deleteLater();
}

void ServerTask::run()
{
    QTimer::singleShot(0, this, SLOT(setup()));
    exec();
    cleanup();
    //QTimer::singleShot(0, this, SLOT(cleanup()));
}

void ServerTask::readyCommand()
{
    QTcpSocket *client = (QTcpSocket*)sender();
    QByteArray arr = client->readAll();
    if(!arr.isEmpty()){
        QString line = QString::fromUtf8(client->readLine()).trimmed();

        optra()->debug(QString("Client command:%1").arg(QString(arr)));
        if (!environment->exec(arr)){
            result(QString("command failed:%1").arg(QString(arr)));
            //QTimer::singleShot(100, this, SLOT(quit()));
        }else
            result(" ");

        client->flush();
    }
}

void ServerTask::disconnected()
{
    QTcpSocket *client = (QTcpSocket*)sender();
    optra()->info(QString("Client disconnected:%1").arg(client->peerAddress().toString()));
    quit();
}
